<?php /** @noinspection SpellCheckingInspection */
    header('content-type:text/html;charset=utf-8');
    //获取前段输入的数据
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    $cpassword = trim($_POST['cpassword']);
    $sex = $_POST['sex'];   //1 or 0
    $email = $_POST['email'];
    $fav = @implode(',', $_POST['fav']);

    include_once "connect.php";

    //！！！注册前必要验证
    //用户名和密码都必须填写
    if(!strlen($username) || !strlen($password)){
        echo "<script>alert('用户名和密码都必须填写');history.back()</script>";    //history.back返回上一级
        exit;
    } else if(!preg_match("/^[a-zA-Z0-9]{3,10}$/", $username)) {
        echo "<script>alert('输入的用户名不符合规范');history.back()</script>";
        exit;
    }
    //前后密码
    if($password != $cpassword){
        echo "<script>alert('两次输入的密码不相同');history.back()</script>";
        exit;
    } else if(!preg_match("/^[a-zA-Z0-9_*]{6,10}$/", $password)) {
        echo "<script>alert('密码填写不符合规范');history.back()</script>";
        exit;
    }
    //验证邮箱
    if(!empty($email)){
        if(!preg_match("/^[a-zA-Z0-9_\-]+@([a-zA-Z0-9]+\.)+(com|cn|net|org)$/",$email)){
            echo "<script>alert('邮箱不符合规范');history.back()</script>";
            exit;
        }
    }

    //该用户在数据库中是否存在
    $sql = "select * from info where username='$username'";
    $result = mysqli_query($conn, $sql);
    $num = mysqli_num_rows($result);
    if($num) {
        echo "<script>alert('该用户已经存在');history.back()</script>";
        exit;
    }

    //sql语句
/** @noinspection SqlNoDataSourceInspection */
$sql = "insert into info (username,password,sex,email,fav,createtime) values ('$username', '".md5($password)."', '$sex', '$email', '$fav', '".time()."')";

$result = mysqli_query($conn, $sql);
    if($result){
        echo "<script>alert('数据插入成功');location.href='index.php'</script>";
    } else {
        //如果数据不符合规范则不插入数据
        echo "<script>alert('数据插入失败');history.back()</script>";
//        exit(mysqli_error($conn));
    }